import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Modal, Upload } from 'antd';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { getToken, getAuth } from '@/utils/localToken';
// TODO： 后期要重写
const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const UploadImg: React.FC = (props) => {
  const {files, getUrl} = props
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([
    { url: files },
  ]);

  const handleCancel = () => setPreviewOpen(false);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList); 
  }

  const onSuccess = ({ data }) => {
    setFileList([data])
    getUrl(data.url)
  }
    

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}></div>
    </div>
  );
  return (
    <>
      <Upload
        name="multipartFile"
        action="/api/oss/uploadFile"
        listType="picture-card"
        headers={{ 'token': 'as2rng!3l3n1s2kj2#' }}
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        onSuccess={onSuccess}
      >
        {fileList.length === 1 ? null : uploadButton}
      </Upload>
      <Modal open={previewOpen} title='预览' footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={files} />
      </Modal>
    </>
  );
};

export default UploadImg;